import { memo, useCallback, useEffect, useState } from 'react';
import type { ReactNode, FC } from 'react';
import { RadioItemWrapper } from './style';
import { RadioIDMap, RadioRecommended } from '@/assets/data/loacl_data';
import { getDjRadioHot, getDjRecommendByType } from '@/views/discover/c-components/redio/service/redio';
import CommonHeader from '@/components/common-header';
import RadioShowItem from '@/components/radio-show-item';
import { Pagination } from 'antd';
interface IProps {
  children?: ReactNode;
  name: string;
  detail?: boolean;
}

const RadioItem: FC<IProps> = (props) => {
  const { name, detail = false } = props;
  const [radio, setRadio] = useState<any>(null);
  const [radioInfo, setRadioInfo] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [offset, setOffset] = useState(1);
  const id = RadioIDMap[name];
  async function getInfo() {
    const res: any = await getDjRecommendByType(RadioIDMap[name]);
    setRadioInfo(res.djRadios);
  }
  useEffect(() => {
    if (!detail) getInfo();
  }, []);
  const limit = 10;
  let radioTotal = 0;
  let total = 0;
  if (radio) {
    radioTotal = radio.count;
    total = Math.ceil(radioTotal / limit);
  }
  useEffect(() => {
    fetchradio();
  }, [offset]);
  const fetchradio = useCallback(async () => {
    setIsLoading(false);
    try {
      const response: any = await getDjRadioHot({ cateId: id, limit: limit - 3, offset: (offset - 1) * limit });
      setRadioInfo(response.djRadios);
      setRadio(response);
    } catch (error) {
      console.log('ERROR', error);
    } finally {
      setIsLoading(true);
    }
  }, [id, offset]);

  const handlePgChange = useCallback((page: number) => {
    setOffset(page);
  }, []);

  return (
    <RadioItemWrapper>
      {detail === false && (
        <CommonHeader
          icon={''}
          iconShow={false}
          name={name}
          moreLink={`categroy?id=${id}`}
          keywords={[]}
          nameSize="large"
        ></CommonHeader>
      )}
      <div className="radio_content">
        {radioInfo.map((item, index) => {
          return (
            <RadioShowItem
              key={index}
              url={item.picUrl}
              name={item.name}
              content={item.rcmdtext}
              id={item.id}
            ></RadioShowItem>
          );
        })}
      </div>
      {detail && (
        <Pagination
          defaultCurrent={offset}
          total={total}
          showSizeChanger={false}
          align="center"
          onChange={handlePgChange}
        />
      )}
    </RadioItemWrapper>
  );
};

export default memo(RadioItem);
